use clap::Parser;
use csv::Reader;
use csv::Writer;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

#[derive(Parser, Debug)]
#[command(name = "rcli", version, author = "xuyifei")]
struct Cli {
    #[command(subcommand)]
    command: Subcommand,
}
#[derive(Parser, Debug)]
enum Subcommand {
    #[command(name = "csv", about = "转化  csv 到 JSON")]
    Csv(CsvOpts),
}

#[derive(Parser, Debug)]
struct CsvOpts {
    #[arg(short, long, value_parser=verify_file_exist)]
    input: String,

    #[arg(short, long, default_value = "output.json")]
    output: String,

    #[arg(short, long, default_value_t = ',')]
    delimiter: char,

    #[arg(long, default_value_t = true)]
    header: bool,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
struct CsvData {
    // #[serde(rename = "Name")]
    name: String,
    #[serde(rename = "Age")]
    age: i32,
    #[serde(rename = "City")]
    city: String,
}
fn main() -> anyhow::Result<()> {
    let opts = Cli::parse();
    match opts.command {
        Subcommand::Csv(opts) => {
            let input_file = opts.input;
            let _output_file = opts.output;
            // let delimiter = opts.delimiter;
            // let header = opts.header;

            let mut rdr = Reader::from_path(input_file)?;
            let mut ret = Vec::with_capacity(128);
            // let mut wtr = Writer::from_path(output_file).expect("Unable to create writer");

            let records = rdr.deserialize::<CsvData>();

            for result in records {
                let record: CsvData = result?;
                ret.push(record);
                // println!("{:?}", record.name);
            }
            let json = serde_json::to_string_pretty(&ret)?;
            fs::write(_output_file, json)?
        }
    }
    Ok(())
    // 创建一个 CSV 文件
    // let mut wtr = Writer::from_path("output.csv").expect("Unable to create writer");

    // // 写入 CSV 文件的表头
    // wtr.write_record(&["Name", "Age", "City"])
    //     .expect("Unable to write record");

    // // 写入 CSV 文件的数据
    // // 写入 CSV 文件的数据
    // let records = vec![
    //     vec!["Alice", "25", "New York"],
    //     vec!["Bob", "30", "Los Angeles"],
    //     vec!["Charlie", "28", "Chicago"],
    // ];

    // for _record in records.iter() {
    //     print!("{:?}", _record);
    //     wtr.write_record(_record).expect("Unable to write record");
    // }

    // // 冲刷缓冲区以确保所有数据都写入文件
    // wtr.flush().expect("Unable to flush records to file");
}

fn verify_file_exist(file_name: &str) -> Result<String, String> {
    if Path::new(file_name).exists() {
        return Ok(file_name.to_string());
    }
    return Err(format!("{} 文件不存在", file_name));
}
